import {mockRequest, request} from '../request';
import {refreshTokenHandler} from "@/service/request/helpers";
import {localStg, sessionStg} from "@/utils";

const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded';

/**
 * 获取验证码
 * @param phone - 手机号
 * @returns - 返回boolean值表示是否发送成功
 */
export function fetchSmsCode(phone: string) {
	return mockRequest.post<boolean>('/getSmsCode', {phone});
}

/**
 * 登录
 * @param userName - 用户名
 * @param password - 密码
 */
export function fetchLogin(userName: string, password: string) {
	return mockRequest.post<ApiAuth.Token>('/login', {userName, password});
}

/** 获取用户信息 */
export function fetchUserInfo() {
	return mockRequest.get<ApiAuth.UserInfo>('/getUserInfo');
}

/**
 * 获取用户路由数据
 * @param userId - 用户id
 * @description 后端根据用户id查询到对应的角色类型，并将路由筛选出对应角色的路由数据返回前端
 */
export function fetchUserRoutes(userId: string) {
	return mockRequest.post<ApiRoute.Route>('/getUserRoutes', {userId});
}

/**
 * 刷新token
 * @param refreshToken
 */
export function fetchUpdateToken(refreshToken: string) {
	return mockRequest.post<ApiAuth.Token>('/updateToken', {refreshToken});
}

/**
 * 对接后端登陆
 * @param userName
 * @param password
 * @param grantType
 */
export function remoteFetchLogin(userName: string, password: string, grantType: string) {
	const basicAuth = "basic bWVzc2FnaW5nLWNsaWVudDpzZWNyZXQ=";
	sessionStg.set('basicAuth', basicAuth)
	return request.post(
		'/auth/oauth2/token',
		{username: userName, password, grant_type: grantType},
		{
			headers: {
				skipToken: true,
				'Content-Type': FORM_CONTENT_TYPE,
				Authorization: basicAuth
			},
		}
	);
}

/** 对接后端获取用户信息 */
export function remoteFetchUserInfo() {
	return request.get('/auth/token/getUserInfo');
}

/**
 * 获取用户路由数据
 * @param userId - 用户id
 * @description 后端根据用户id查询到对应的角色类型，并将路由筛选出对应角色的路由数据返回前端
 */
export function remoteFetchUserRoutes(tenantId: string, userId: string) {
	return request.get(`/system/menu/getUserRoutes/${tenantId}/${userId}`);
}

/**
 * 刷新token
 * @param refreshToken
 */
export function remoteFetchUpdateToken(refreshToken: string) {
	return request.post(
		'/auth/oauth2/token',
		{grant_type: 'refresh_token', refresh_token: refreshToken},
		{
			headers:
				{
					skipToken: true,
					Authorization: sessionStg.get("basicAuth"),
					'Content-Type': FORM_CONTENT_TYPE,
				}
		}
	);
}


/**
 * 退出登陆移除token
 * @param token
 */
export function remoteRemoveToken(token: string) {
	return request.delete('/auth/token/' + token, {
		headers: {
			skipToken: true,
			Authorization: sessionStg.get("basicAuth")
		},
	});
}

/**
 * 校验令牌，若有效期小于半小时自动续期
 * @param refreshTime
 * @param refreshLock
 */
export function checkToken(refreshTime: number, refreshLock: boolean) {
	return request.get('/auth/token/checkToken', {
		headers: {
			skipToken: true,
			'Content-Type': '',
		},
		params: {token: localStg.get("token")}
	}).then((response) => {
		if (response.code !== 200) {
			clearInterval(refreshTime);
			return;
		}
		const expire = response.data;
		if (expire) {
			const expiredPeriod = expire - new Date().getTime();
			//小于半小时自动续约
			if (expiredPeriod <= 30 * 60 * 1000) {
				if (!refreshLock) {
					refreshLock = true;
					refreshTokenHandler()
						.catch(() => {
							clearInterval(refreshTime);
						})
					refreshLock = false;
				}
			}
		}
	}).catch(() => {
		// 发生异常关闭定时器
		clearInterval(refreshTime);
	});
}
